import { ref, computed, reactive, onMounted } from 'vue'
import type { 
  TodoItem, 
  TodoCategory, 
  CreateTodoRequest, 
  UpdateTodoRequest, 
  TodoFilter, 
  TodoSort
} from '../types'
import { TodoStatus } from '../types'
import { todoApi, type TodoListQuery } from '../api'
import { categoryApi } from '../api'

export function useTodos() {
  const todos = ref<TodoItem[]>([])
  const categories = ref<TodoCategory[]>([])
  const loading = ref(false)
  
  // 视图模式
  const viewMode = ref<'list' | 'grid' | 'flexbox'>('grid')
  
  // 过滤器和排序
  const filter = reactive<TodoFilter>({})
  const sort = reactive<TodoSort>({
    field: 'createdAt',
    order: 'desc'
  })

  // 当前查询参数
  const currentQuery = ref<TodoListQuery>({})

  // 统计信息计算基于原始数据
  const allTodos = ref<TodoItem[]>([])

  // 根据当前筛选条件加载待办事项
  const loadTodosWithFilter = async () => {
    loading.value = true
    try {
      const query: TodoListQuery = {}

      // 构建查询参数
      if (filter.categoryId !== undefined) {
        query.categoryId = filter.categoryId
      }

      if (filter.status && filter.status.length === 1) {
        query.status = filter.status[0]
      }

      if (filter.priority && filter.priority.length === 1) {
        query.priority = filter.priority[0]
      }

      if (filter.keyword) {
        query.keyword = filter.keyword
      }

      if (filter.isFavorite) {
        query.isFavorite = filter.isFavorite
      }

      currentQuery.value = query
      const todoList = await todoApi.getList(query)
      todos.value = todoList

      // 更新全量数据用于统计
      if (Object.keys(query).length === 0) {
        // 如果没有筛选条件，当前数据就是全量数据
        allTodos.value = todoList
      }
      // 如果有筛选条件，暂时不重复获取全量数据，使用现有数据进行统计

    } catch (error) {
      console.error('加载待办事项失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 统计信息（基于全量数据）
  const stats = computed(() => {
    const data = allTodos.value.length > 0 ? allTodos.value : todos.value
    const total = data.length
    const completed = data.filter(todo => todo.status === TodoStatus.COMPLETED).length
    const inProgress = data.filter(todo => todo.status === TodoStatus.IN_PROGRESS).length
    const pending = data.filter(todo => todo.status === TodoStatus.TODO).length
    
    return {
      total,
      completed,
      inProgress,
      pending,
      completionRate: total > 0 ? Math.round((completed / total) * 100) : 0
    }
  })

  // 创建待办事项
  const createTodo = async (request: CreateTodoRequest): Promise<TodoItem> => {
    loading.value = true
    try {
      const newTodo = await todoApi.create(request)
      // 重新加载数据以确保列表最新
      await loadTodosWithFilter()
      return newTodo
    } finally {
      loading.value = false
    }
  }

  // 更新待办事项
  const updateTodo = async (id: string, request: UpdateTodoRequest): Promise<TodoItem> => {
    loading.value = true
    try {
      const updatedTodo = await todoApi.update(id, request)
      // 重新加载数据以确保列表最新
      await loadTodosWithFilter()
      return updatedTodo
    } finally {
      loading.value = false
    }
  }

  // 删除待办事项
  const deleteTodo = async (id: string): Promise<void> => {
    loading.value = true
    try {
      await todoApi.delete(id)
      // 重新加载数据
      await loadTodosWithFilter()
    } finally {
      loading.value = false
    }
  }

  // 批量更新状态
  const batchUpdateStatus = async (ids: string[], status: TodoStatus): Promise<void> => {
    loading.value = true
    try {
      await todoApi.batchUpdateStatus(ids, status)
      // 重新加载数据
      await loadTodosWithFilter()
    } finally {
      loading.value = false
    }
  }

  // 切换完成状态
  const toggleTodoStatus = async (id: string): Promise<void> => {
    loading.value = true
    try {
      await todoApi.toggleStatus(id)
      // 重新加载数据
      await loadTodosWithFilter()
    } finally {
      loading.value = false
    }
  }

  // 获取分类映射
  const getCategoryById = (id: string) => {
    return categories.value.find(cat => cat.id === id)
  }

  // 获取分类的待办数量（基于全量数据）
  const getCategoryTodoCount = (categoryId: string) => {
    const data = allTodos.value.length > 0 ? allTodos.value : todos.value
    return data.filter(todo => todo.categoryId === categoryId).length
  }

  // 获取未分类的待办数量
  const getUncategorizedTodoCount = () => {
    const data = allTodos.value.length > 0 ? allTodos.value : todos.value
    return data.filter(todo => !todo.categoryId).length
  }

  // 重置过滤器
  const resetFilter = () => {
    Object.keys(filter).forEach(key => {
      delete filter[key as keyof TodoFilter]
    })
    // 重新加载数据
    loadTodosWithFilter()
  }

  // 过滤器变化时重新加载数据
  const applyFilter = () => {
    loadTodosWithFilter()
  }

  // 加载待办事项数据（废弃，使用 loadTodosWithFilter）
  const loadTodos = async () => {
    await loadTodosWithFilter()
  }

  // 加载分类数据
  const loadCategories = async () => {
    try {
      const categoryList = await categoryApi.tree({ type: 'TODO' })
      categories.value = categoryList
    } catch (error) {
      console.error('加载分类失败:', error)
    }
  }

  // 初始化数据
  const init = async () => {
    await loadCategories()
    await loadTodosWithFilter()
  }
  
  // 专门用于首次加载的函数，会确保获取全量数据用于统计
  const initWithStats = async () => {
    await loadCategories()
    
    // 如果有筛选条件，先获取全量数据用于统计
    if (Object.keys(filter).some(key => filter[key as keyof TodoFilter] !== undefined)) {
      const allData = await todoApi.getList()
      allTodos.value = allData
    }
    
    // 然后根据筛选条件加载显示数据
    await loadTodosWithFilter()
  }

  // 组件挂载时加载数据（可选）
  const autoInit = (enabled = true) => {
    if (enabled) {
      onMounted(() => {
        init()
      })
    }
  }

  // 切换视图模式
  const toggleViewMode = () => {
    viewMode.value = viewMode.value === 'list' ? 'grid' : 'list'
  }

  return {
    // 数据
    todos,
    categories,
    loading,
    filter,
    sort,
    stats,
    viewMode,
    
    // 方法
    createTodo,
    updateTodo,
    deleteTodo,
    batchUpdateStatus,
    toggleTodoStatus,
    getCategoryById,
    getCategoryTodoCount,
    getUncategorizedTodoCount,
    resetFilter,
    applyFilter,
    loadTodos,
    loadCategories,
    init,
    initWithStats,
    autoInit,
    toggleViewMode
  }
}